import behavior from './behavior/index'
import error from './error/index'
import performance from './performance/index'

import { setConfig } from './config/index'
import { lazyBatchReport } from './report/index'

window.__webSDK__ = {
  version: '0.0.1',
}

// 针对vue
export function install(app, options) {
  if (!!__webSDK__.vue) return
  __webSDK__.vue = app

  setConfig(options)

  const handler = app.config.errorHandler

  // 在Vue项目中 通过 vue.config.errorHandler 监听全局异常
  app.config.errorHandler = function (err, vm, info) {
    const reportData = {
      info,
      error: err.stack,
      subType: 'vue',
      type: 'error',
      startTime: window.performance.now(),
      pageUrl: window.location.href,
    }

    // vue 异常上报
    lazyBatchReport(reportData)

    if (handler) {
      handler.call(this, err, vm, info)
    }
  }
}

// 针对react
export function errorBoundary(err, info) {
  if (!!__webSDK__.react) return
  __webSDK__.vue = true

  const reportData = {
    info,
    error: err.stack,
    subType: 'react',
    type: 'error',
    startTime: window.performance.now(),
    pageUrl: window.location.href,
  }

  // react 异常上报
  lazyBatchReport(reportData)
}

export function init(opts) {
  setConfig(opts)

  // 初始化
  behavior()
  error()
  performance()
}

export default {
  install,
  errorBoundary,
  behavior,
  error,
  performance,
  init,
}
